package com.jwater.core.net;

import java.io.Serializable;

import com.jwater.core.serialize.SerializeUtils;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class FilePacket implements Serializable {

    private static final long serialVersionUID = 7341828203314072658L;
    public static final short TYPE_BEGIN = 0;
    public static final short TYPE_DATA = 1;
    public static final short TYPE_END = 2;
    public static final short TYPE_ERROR = 3;

    private short type;
    private String category;
    private String fileName;
    private int index;
    private byte[] data;
    private String errorMsg = "";

    public byte[] serialize() throws Exception {
        if (type == TYPE_BEGIN) {
            return SerializeUtils.serializeArray(type, category, fileName);
        } else if (type == TYPE_DATA) {
            return SerializeUtils.serializeArray(type, category, fileName, index, data);
        } else if (type == TYPE_END) {
            return SerializeUtils.serializeArray(type, category, fileName, index);
        } else if (type == TYPE_ERROR) {
            return SerializeUtils.serializeArray(type, category, fileName, errorMsg);
        }
        return null;
    }

    public FilePacket deserialize(byte[] data) throws Exception {
        Object[] objs = SerializeUtils.deserializeArray(data);
        type = (short) objs[0];
        category = (String) objs[1];
        fileName = (String) objs[2];
        if (type == TYPE_DATA || type == TYPE_END) {
            index = (int) objs[3];
        }
        if (type == TYPE_DATA) {
            this.data = (byte[]) objs[4];
        }
        if (type == TYPE_ERROR) {
            this.errorMsg = (String) objs[3];
        }
        return this;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public short getType() {
        return type;
    }

    public void setType(short type) {
        this.type = type;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    @Override
    public String toString() {
        return "FilePacket [type=" + type + ", category=" + category + ", fileName=" + fileName + ", index=" + index
                + "]";
    }
}
